package net.lahuobao.mall.controller.admin;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.lahuobao.mall.entity.admin.MallRegionEntity;
import net.lahuobao.mall.service.admin.MallRegionServiceI;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.DataGridReturn;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import net.lahuobao.mall.entity.admin.MallEtcLivetakeAddressEntity;
import net.lahuobao.mall.service.admin.MallEtcLivetakeAddressServiceI;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;

import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author zhangdaihao
 * @version V1.0
 * @Title: Controller
 * @Description: 商城ETC卡现场领卡地址
 * @date 2016-12-05 13:59:26
 */
@Controller
@RequestMapping("/mallEtcLivetakeAddressController")
public class MallEtcLivetakeAddressController extends BaseController {
    /**
     * Logger for this class
     */
    private static final Logger logger = Logger.getLogger(MallEtcLivetakeAddressController.class);

    @Autowired
    private MallEtcLivetakeAddressServiceI mallEtcLivetakeAddressService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private Validator validator;

    @Autowired
    private MallRegionServiceI regionService;


    /**
     * 商城ETC卡现场领卡地址列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView("net/lahuobao/mall/admin/mallEtcLivetakeAddressList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(MallEtcLivetakeAddressEntity mallEtcLivetakeAddress, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
        CriteriaQuery cq = new CriteriaQuery(MallEtcLivetakeAddressEntity.class, dataGrid);
        //查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallEtcLivetakeAddress, request.getParameterMap());
        DataGridReturn temp = this.mallEtcLivetakeAddressService.getDataGridReturn(cq, true);
        List<MallEtcLivetakeAddressEntity> list = temp.getRows();
        for (MallEtcLivetakeAddressEntity entity : list) {
            String[] str = regionService.getAddressByCode(Integer.parseInt(entity.getAreacode())).split(";");
            String reStr = "";
            for (int i = 0; i < str.length; i++) {
                reStr += str[i].split("_")[0];
            }
            entity.setAreacodeStr(reStr);
        }
        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除商城ETC卡现场领卡地址
     *
     * @return
     */
    @RequestMapping(params = "del")
    @ResponseBody
    public AjaxJson del(MallEtcLivetakeAddressEntity mallEtcLivetakeAddress, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        mallEtcLivetakeAddress = systemService.getEntity(MallEtcLivetakeAddressEntity.class, mallEtcLivetakeAddress.getId());
        message = "商城ETC卡现场领卡地址删除成功";
        //判断条数
        List<MallEtcLivetakeAddressEntity> lists = mallEtcLivetakeAddressService.loadAll(MallEtcLivetakeAddressEntity.class);
        //至少保留一条
        if(lists.size() == 1){
            j.setSuccess(false);
            message = "删除失败！至少保留一条记录";
        }else{
            mallEtcLivetakeAddressService.delete(mallEtcLivetakeAddress);
            systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
        }
        j.setMsg(message);
        return j;
    }


    /**
     * 添加商城ETC卡现场领卡地址
     *
     * @param
     * @return
     */
    @RequestMapping(params = "save")
    @ResponseBody
    public AjaxJson save(MallEtcLivetakeAddressEntity mallEtcLivetakeAddress, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        if (StringUtil.isNotEmpty(mallEtcLivetakeAddress.getId())) {
            message = "商城ETC卡现场领卡地址更新成功";
            MallEtcLivetakeAddressEntity t = mallEtcLivetakeAddressService.get(MallEtcLivetakeAddressEntity.class, mallEtcLivetakeAddress.getId());
            try {
                MyBeanUtils.copyBeanNotNull2Bean(mallEtcLivetakeAddress, t);
                mallEtcLivetakeAddressService.saveOrUpdate(t);
                systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
            } catch (Exception e) {
                e.printStackTrace();
                message = "商城ETC卡现场领卡地址更新失败";
            }
        } else {
            message = "商城ETC卡现场领卡地址添加成功";
            mallEtcLivetakeAddress.setCreatetime(new Date());
            mallEtcLivetakeAddressService.save(mallEtcLivetakeAddress);
            systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 商城ETC卡现场领卡地址列表页面跳转
     *
     * @return
     */
    @RequestMapping(params = "addorupdate")
    public ModelAndView addorupdate(MallEtcLivetakeAddressEntity mallEtcLivetakeAddress, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(mallEtcLivetakeAddress.getId())) {
            mallEtcLivetakeAddress = mallEtcLivetakeAddressService.getEntity(MallEtcLivetakeAddressEntity.class, mallEtcLivetakeAddress.getId());
            req.setAttribute("mallEtcLivetakeAddressPage", mallEtcLivetakeAddress);
            req.setAttribute("addressCodeStr", regionService.getAddressByCode(Integer.parseInt(mallEtcLivetakeAddress.getAreacode())));
        }
        //获取全国省份
        CriteriaQuery cq = new CriteriaQuery(MallRegionEntity.class);
        cq.eq("regionLevel", 1);
        cq.add();
        List<MallRegionEntity> regions = regionService.getListByCriteriaQuery(cq, false);
        req.setAttribute("regions", regions);

        return new ModelAndView("net/lahuobao/mall/admin/mallEtcLivetakeAddress");
    }

    /**
     * 根据负id_(code)获取子节点
     *
     * @param code
     * @return
     */
    @RequestMapping(params = "addressByCode", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson getAddressByCode(String code) {
        String message = null;
        AjaxJson j = new AjaxJson();
        try {
            if (StringUtil.isNotEmpty(code)) {
                CriteriaQuery cq = new CriteriaQuery(MallRegionEntity.class);
                cq.eq("parentId", code);
                cq.add();
                List<MallRegionEntity> regions = regionService.getListByCriteriaQuery(cq, false);
                j.setObj(regions);
            }
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("系统异常！");
            e.printStackTrace();
        }
        j.setMsg(message);
        return j;
    }

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<MallEtcLivetakeAddressEntity> list() {
        List<MallEtcLivetakeAddressEntity> listMallEtcLivetakeAddresss = mallEtcLivetakeAddressService.getList(MallEtcLivetakeAddressEntity.class);
        return listMallEtcLivetakeAddresss;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> get(@PathVariable("id") String id) {
        MallEtcLivetakeAddressEntity task = mallEtcLivetakeAddressService.get(MallEtcLivetakeAddressEntity.class, id);
        if (task == null) {
            return new ResponseEntity(HttpStatus.NOT_FOUND);
        }
        return new ResponseEntity(task, HttpStatus.OK);
    }

    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<?> create(@RequestBody MallEtcLivetakeAddressEntity mallEtcLivetakeAddress, UriComponentsBuilder uriBuilder) {
        //调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
        Set<ConstraintViolation<MallEtcLivetakeAddressEntity>> failures = validator.validate(mallEtcLivetakeAddress);
        if (!failures.isEmpty()) {
            return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
        }

        //保存
        mallEtcLivetakeAddressService.save(mallEtcLivetakeAddress);

        //按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
        String id = mallEtcLivetakeAddress.getId().toString();
        URI uri = uriBuilder.path("/rest/mallEtcLivetakeAddressController/" + id).build().toUri();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(uri);

        return new ResponseEntity(headers, HttpStatus.CREATED);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> update(@RequestBody MallEtcLivetakeAddressEntity mallEtcLivetakeAddress) {
        //调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
        Set<ConstraintViolation<MallEtcLivetakeAddressEntity>> failures = validator.validate(mallEtcLivetakeAddress);
        if (!failures.isEmpty()) {
            return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
        }

        //保存
        mallEtcLivetakeAddressService.saveOrUpdate(mallEtcLivetakeAddress);

        //按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
        return new ResponseEntity(HttpStatus.NO_CONTENT);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable("id") String id) {
        mallEtcLivetakeAddressService.deleteEntityById(MallEtcLivetakeAddressEntity.class, id);
    }
}
